package com.woollen.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woollen.common.BaseResponse;
import com.woollen.common.ResultUtils;
import com.woollen.model.Member;
import com.woollen.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import org.springframework.util.DigestUtils;

@RestController
@RequestMapping("/api/admin/member")
public class AdminMemberController {
    @Autowired
    private MemberService memberService;

    // 分页查询
    @GetMapping("/list")
    public BaseResponse<Page<Member>> list(@RequestParam(defaultValue = "1") long page,
                                           @RequestParam(defaultValue = "10") long size,
                                           @RequestParam(required = false) String name,
                                           @RequestParam(required = false) String phone) {
        QueryWrapper<Member> qw = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) qw.like("name", name);
        if (phone != null && !phone.isEmpty()) qw.like("phone", phone);
        Page<Member> memberPage = memberService.page(new Page<>(page, size), qw);
        return ResultUtils.success(memberPage);
    }

    // 查询详情
    @GetMapping("/{id}")
    public BaseResponse<Member> detail(@PathVariable Integer id) {
        Member member = memberService.getById(id);
        return ResultUtils.success(member);
    }

    // 新增
    @PostMapping
    public BaseResponse<Integer> add(@RequestBody Member member) {
        if (member.getPassword() == null || member.getPassword().isEmpty()) {
            String defaultPwd = DigestUtils.md5DigestAsHex("123456".getBytes());
            member.setPassword(defaultPwd);
        }
        memberService.save(member);
        return ResultUtils.success(member.getMbid());
    }

    // 修改
    @PutMapping
    public BaseResponse<Boolean> update(@RequestBody Member member) {
        boolean res = memberService.updateById(member);
        return ResultUtils.success(res);
    }

    // 删除
    @DeleteMapping("/{id}")
    public BaseResponse<Boolean> delete(@PathVariable Integer id) {
        boolean res = memberService.removeById(id);
        return ResultUtils.success(res);
    }

    // 批量删除
    @DeleteMapping("/batch")
    public BaseResponse<Boolean> batchDelete(@RequestBody List<Long> ids) {
        boolean res = memberService.removeByIds(ids);
        return ResultUtils.success(res);
    }

    @PostMapping("/import")
    public BaseResponse<Boolean> importMembers(@RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            List<Member> memberList = EasyExcel.read(inputStream)
                .head(Member.class)
                .sheet()
                .doReadSync();
            // 批量处理密码
            String defaultPwd = DigestUtils.md5DigestAsHex("123456".getBytes());
            for (Member member : memberList) {
                if (member.getPassword() == null || member.getPassword().isEmpty()) {
                    member.setPassword(defaultPwd);
                }
            }
            memberService.saveBatch(memberList);
            return ResultUtils.success(true);
        } catch (Exception e) {
            return ResultUtils.error(500, "导入失败: " + e.getMessage());
        }
    }

    @PostMapping("/admin/login")
    public BaseResponse<Member> adminLogin(@RequestBody Member req) {
        String username = req.getPhone() != null ? req.getPhone() : req.getEmail();
        Member admin = memberService.adminLogin(username, req.getPassword());
        return ResultUtils.success(admin);
    }
} 